package com.store.bookstore_backend.service;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

@Service
public class  FileStorageService {
    private final Path fileStorageLocation;

    public FileStorageService(@Value("${file.upload-dir}") String uploadDir) {
        this.fileStorageLocation = Paths.get(uploadDir).toAbsolutePath().normalize();

        try {
            Files.createDirectories(this.fileStorageLocation);
        } catch (Exception ex) {
            throw new RuntimeException("无法创建上传目录: " + ex.getMessage());
        }
    }

    public String storeFile(MultipartFile file) {
        // 清理文件名，防止路径遍历攻击
        String fileName = Paths.get(file.getOriginalFilename()).getFileName().toString();

        try {
            // 检查文件名是否有效
            if (fileName.contains("..")) {
                throw new RuntimeException("无效的文件路径: " + fileName);
            }

            // 生成唯一文件名以避免冲突
            String uniqueFileName = System.currentTimeMillis() +"_"+ fileName;

            // 复制文件到目标位置（替换现有文件）
            Path targetLocation = this.fileStorageLocation.resolve(uniqueFileName);
            Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);

            return uniqueFileName;
        } catch (IOException ex) {
            throw new RuntimeException("无法存储文件 " + fileName + ". 请再试一次!", ex);
        }
    }
}
